package com.jinzhi.jzweb.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.domain.Tree;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.utils.BuildTree;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.sys.domain.MenuDO;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 
 * <pre>
 * 班级课程表
 * </pre>
 * <small> 2020-02-24 21:00:12 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/coursesClass")
public class CoursesClassController extends BaseController {
    @Autowired
    private CoursesClassService coursesClassService;
    @Autowired
    private CoursesService coursesService;
    @Autowired
	private ClassesService classesService;
    @Autowired
    private StuClassService stuClassService;
	@Autowired
	private UserService userService;
	@Autowired
	private OrganizationNewsService organizationNewsService;
    @Autowired
    private CertificateProfileService certificateProfileService;
    @Autowired
    private DictService dictService;
    @Autowired
    private OrganizationRolesService organizationRolesService;

	@GetMapping()
	@RequiresPermissions("jzweb:coursesClass:coursesClass")
	String Classes(){
	    return "jzweb/coursesClass/coursesClass";
	}

	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jzweb:coursesClass:coursesClass")
    public Result<Page<CoursesClassDO>> list(String class_id, String courseName, String teacherName, String profileName) {

        Wrapper<CoursesClassDO> wrapper = new EntityWrapper<CoursesClassDO>().orderBy("id", false);
        if (class_id != null && !class_id.equals("")){
            wrapper.eq("class_id", Long.valueOf(class_id));
        }
        List<CoursesClassDO> list = new ArrayList<>();
        Page<CoursesClassDO> page = coursesClassService.selectPage(getPage(CoursesClassDO.class), wrapper);
        System.out.println("page.getRecords().size():"+page.getRecords().size());
        for (int i = 0; i < page.getRecords().size(); i++) {
            CoursesClassDO coursesClassDO = (CoursesClassDO) page.getRecords().get(i);

            Wrapper<CoursesDO> CoursesWrapper = new EntityWrapper<CoursesDO>().orderBy("id", false);
            //机构
            String roleName = getRoleNames();
            if (!roleName.contains("超级用户角色")) {
                CoursesWrapper.eq("org_id", this.getUser().getOrgId());
                System.out.println("org_id:" + this.getUser().getOrgId());
            }

            //课程名称
            if(courseName!=null && !courseName.equals("")) {
                CoursesWrapper.like("name", courseName);
            }
            //讲师名称
            if (teacherName != null && !teacherName.equals("")) {
                Wrapper<UserDO> uWrapper = new EntityWrapper<UserDO>().like("name", teacherName);
                List<UserDO>  userDOS = userService.selectList(uWrapper);
                String str = "";
                for (UserDO userDO : userDOS){
                    str = str + userDO.getId() + ",";
                }
                if(StringUtils.isNotBlank(str)){
                    CoursesWrapper.in("user_id",str.substring(0,str.length()-1));
                }else{
                    CoursesWrapper.eq("user_id",null);
                }
            }
            if (profileName != null && !profileName.equals("")) {
                Wrapper<CertificateProfileDO> cerWrapper = new EntityWrapper<CertificateProfileDO>().like("name", profileName);
                List<CertificateProfileDO>  certificateProfileDOS = certificateProfileService.selectList(cerWrapper);
                String str = "";
                for (CertificateProfileDO certificateProfileDO : certificateProfileDOS){
                    str = str + certificateProfileDO.getId() + ",";
                }
                if(org.apache.commons.lang3.StringUtils.isNotBlank(str)){
                    CoursesWrapper.in("profile_id",str.substring(0,str.length()-1));
                }else{
                    CoursesWrapper.eq("profile_id",null);
                }
            }
            CoursesWrapper.eq("id", coursesClassDO.getCoursesId());
            System.out.println("CoursesWrapper:"+CoursesWrapper.toString());
            List<CoursesDO> coursesDOS = coursesService.selectList(CoursesWrapper);
            System.out.println("coursesDOS.size():"+coursesDOS.size());
            if (coursesDOS.size() > 0) {
                //课程名
                if(coursesDOS.get(0).getName()!=null){
                    coursesClassDO.setCourseName(coursesDOS.get(0).getName());
                }else {
                    coursesClassDO.setCourseName("");
                }
                //班级名称
                StudentClassesDO sclassDO = this.classesService.selectById(coursesClassDO.getClassId());
                if(sclassDO.getName()!=null){
                    coursesClassDO.setStudentClassName(sclassDO.getName());
                }else {
                    coursesClassDO.setStudentClassName("");
                }
                //班主任
                if(sclassDO.getCreaterId()!=null){
                    UserDO userDO = this.userService.selectById(sclassDO.getCreaterId());
                    if(userDO.getName()!=null) {
                        coursesClassDO.setHeadmasterName(userDO.getName());
                    }else {
                        coursesClassDO.setHeadmasterName("");
                    }
                }else {
                    coursesClassDO.setHeadmasterName("");
                }

                OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(coursesDOS.get(0).getOrgId());
                if(organizationNewsDO != null){
                    coursesClassDO.setOrgName(organizationNewsDO.getName());
                }else{
                    coursesClassDO.setOrgName("");
                }

                CertificateProfileDO  certificateProfileDOS = certificateProfileService.selectById(coursesDOS.get(0).getProfileId());
                if(certificateProfileDOS != null){
                    coursesClassDO.setProfileName(certificateProfileDOS.getName());
                }else{
                    coursesClassDO.setProfileName("");
                }

                UserDO  teacher = userService.selectById(coursesDOS.get(0).getUserId());
                if(teacher != null){
                    coursesClassDO.setTeacherName(teacher.getName());
                }else{
                    coursesClassDO.setTeacherName("");
                }

                UserDO  creater = userService.selectById(coursesClassDO.getCreateUserId());
                if(teacher != null){
                    coursesClassDO.setCreaterName(creater.getName());
                }else{
                    coursesClassDO.setCreaterName("");
                }
                list.add(coursesClassDO);
            }
        }
        if(list.size()>0) {
            page.setRecords(list);
        }else {
            list=null;
            page.setRecords(list);
        }
        return Result.ok(page);
    }


    @GetMapping("/add")
    @RequiresPermissions("jzweb:coursesClass:add")
    String add(Model model){

        String roleName = getRoleNames();
	    //班级
        List<Map> maps = new ArrayList<>();
        Wrapper<StudentClassesDO> StudentClassWrapper = new EntityWrapper<StudentClassesDO>().orderBy("id", false);
        if (!roleName.contains("超级用户角色")) {
            StudentClassWrapper.eq("creater_id", this.getUserId());
        }
        List<StudentClassesDO> studentClassesDOS = classesService.selectList(StudentClassWrapper);
        if(studentClassesDOS.size()>0){
            for (StudentClassesDO s:studentClassesDOS){
                Map newMap = new HashMap();
                newMap.put("id", s.getId());
                newMap.put("name", s.getName());
                maps.add(newMap);
            }
        }
        model.addAttribute("studentClasses",maps);

        if (!roleName.contains("超级用户角色")) {
            List<Map<Object,Object>> list = new ArrayList<>();
            Map<Object,Object> map1 = new HashMap();
            map1.put("id",this.getUser().getOrgId());
            OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(this.getUser().getOrgId());
            if(organizationNewsDO != null){
                map1.put("name",organizationNewsDO.getName());
            }else{
                map1.put("name",this.getUser().getOrgName());
            }
            list.add(map1);
            model.addAttribute("orgNews",list);
        } else {
            model.addAttribute("orgNews",organizationRolesService.selByRoleType(0));
        }
        return "jzweb/coursesClass/add";
    }

       @Log("添加班级课程表")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("jzweb:studentClasses:add")
    public Result<String> save( String courseId, String studentClassId){
        boolean flag = true;
        CoursesClassDO coursesClassDO = new CoursesClassDO();
        if(courseId!=null && !courseId.equals("")){
            coursesClassDO.setCoursesId(Long.valueOf(courseId));
        }else {
            flag = false;
        }
        if(studentClassId!=null && !studentClassId.equals("")){
            coursesClassDO.setClassId(Long.valueOf(studentClassId));
        }else {
            flag = false;
        }
        if(flag) {
            coursesClassDO.setAddTime(new Date());
            coursesClassDO.setCreateUserId(this.getUserId());
            coursesClassService.insert(coursesClassDO);
            return Result.ok();
        }else {
            return Result.fail("参数错误！");
        }
    }

    @Log("添加班级课程表")
    @ResponseBody
    @PostMapping("/savePlan")
    @RequiresPermissions("jzweb:coursesClass:settingCoursePlan")
    public Result<String> savePlan( String id, String startTime, String endTime,
                                    Integer requirement, Integer time_requirement, String time_unit,
                                    Integer range, String courseIds

    ){
	    System.out.println("id:"+id);
        System.out.println("startTime:"+startTime);
        System.out.println("endTime:"+endTime);
        System.out.println("requirement:"+requirement);
        System.out.println("time_requirement:"+time_requirement);
        System.out.println("time_unit:"+time_unit);
        System.out.println("range:"+range);
        System.out.println("courseIds:"+courseIds);

        boolean flag = true;
        CoursesClassDO coursesClassDO = null;
        if(id!=null && !id.equals("")){
            coursesClassDO = coursesClassService.selectById(Long.valueOf(id));
            if(startTime!=null && !startTime.equals("")){
                coursesClassDO.setStartTime(startTime);
            }else {
                flag = false;
            }
            if(endTime!=null && !endTime.equals("")){
                coursesClassDO.setEndTime(endTime);
            }else {
                flag = false;
            }
            if(requirement!=null && !requirement.equals("")){
                coursesClassDO.setRequirement(Integer.valueOf(requirement));
                if(time_requirement!=null && !time_requirement.equals("")){
                    coursesClassDO.setTimeRequirement(time_requirement);
                }else {
                    flag = false;
                }
                if(time_unit!=null && !time_unit.equals("")){
                    coursesClassDO.setTimeUnit(time_unit);
                }else {
                    flag = false;
                }
            }else {
                flag = false;
            }
            if(range!=null && !range.equals("")){
                coursesClassDO.setRange(Integer.valueOf(range));
                if(courseIds!=null && !courseIds.equals("")){
                    coursesClassDO.setCourseIds(courseIds);
                }else {
                    flag = false;
                }
            }else {
                flag = false;
            }

        }else {
            flag = false;
        }

        if(flag) {
            coursesClassDO.setAddTime(new Date());
            coursesClassDO.setCreateUserId(this.getUserId());
            coursesClassService.updateById(coursesClassDO);
            return Result.ok();
        }else {
            return Result.fail("参数错误！");
        }
    }



    @Log("删除班级课程表")
    @PostMapping( "/remove")
    @ResponseBody
    @RequiresPermissions("jzweb:studentClasses:add")
    public Result<String>  remove( Long id){
        coursesClassService.deleteById(id);
        return Result.ok();
    }

    @Log("批量删除班级课程表")
    @PostMapping( "/batchRemove")
    @ResponseBody
    @RequiresPermissions("jzweb:studentClasses:add")
    public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
        coursesClassService.deleteBatchIds(Arrays.asList(ids));
        return Result.ok();
    }


    @GetMapping("/settingCoursePlan/{id}")
    @RequiresPermissions("jzweb:coursesClass:settingCoursePlan")
    String settingCoursePlan(@PathVariable("id") Long id,Model model){
        CoursesClassDO coursesClassDO = this.coursesClassService.selectById(Long.valueOf(id));
        model.addAttribute("coursesClass", coursesClassDO);

        return "jzweb/coursesClass/settingCoursePlan";
    }

    @Log("查询菜单树形数据")
    @GetMapping("/tree")
    @ResponseBody
    Tree<CoursesClassDO> tree(String id) {
        Tree<CoursesClassDO> tree = new Tree<CoursesClassDO>();
        List<Tree<CoursesClassDO>> trees = new ArrayList<Tree<CoursesClassDO>>();
        Wrapper<CoursesClassDO> wrapper = new EntityWrapper<CoursesClassDO>().orderBy("id", false);
        CoursesClassDO course = null;
        if(id!=null && !id.equals("")){
            course = coursesClassService.selectById(Long.valueOf(id));
            wrapper.eq("class_id", course.getClassId());
        }

        List<CoursesClassDO> coursesClassDOS = coursesClassService.selectList(wrapper);
        for (CoursesClassDO c : coursesClassDOS) {
            Tree<CoursesClassDO> t1 = new Tree<CoursesClassDO>();
            t1.setId(c.getCoursesId().toString());
            if(course!=null) {
                boolean isHave = false;
                if(course.getCourseIds()!=null){
                    String[] idLlist = course.getCourseIds().split(",");
                    if(idLlist.length>0){
                        for (int a=0; a<idLlist.length; a++){
                            if(idLlist[a].equals(c.getCoursesId().toString())){
                                isHave = true;
                                break;
                            }
                        }
                    }
                }
                if(isHave) {
                    Map<String, Object> state = new HashMap<>(16);
                    state.put("selected", true);
                    t1.setState(state);
                }
            }
            CoursesDO coursesDO = this.coursesService.selectById(c.getCoursesId());
            if(coursesDO!=null) {
                t1.setText(coursesDO.getName());
            }else {
                t1.setText("");
            }
            trees.add(t1);
        }

        Tree<CoursesClassDO> t = BuildTree.build(trees);
        tree = t;
        return tree;
    }
}


